package karpiel.boguchwal.wojciech.przemek

import karpiel.boguchwal.wojciech.przemek.Ast._

object Bruinizer {
  /**
    * Replaces variable occurences with de-bruijn indices
    */
  def bruinize(expr: Ast)(implicit ctx: Context, cache: Cache): Ast = {
    expr match {
      case PiType(NamedType(name, typeT), value) => PiType(bruinize(typeT), bruinize(value)(ctx.append(typeT, name), implicitly))
      case PiValue(NamedType(name, typeT), value) => PiValue(bruinize(typeT), bruinize(value)(ctx.append(typeT, name), implicitly))
      case Var(name) =>
        Bruijn(ctx.getIndexByName(name), Some(name))
      //---
      case q: NamedType => throw new BruinizationException("Poza deklaracją funkcji znikąd się wziął co to w ogóle jest $q")
      case any => Utils.applyToSubTrees(any, bruinize)
    }
  }

  class BruinizationException(msg: String) extends TypecheckException(msg)
}

/*
 case PiType(NamedType(name, typeT), value) => PiType(bruinize(typeT),bruinize(value)(ctx.append(typeT,name)))
      case PiValue(NamedType(name, typeT), value) => PiValue(bruinize(typeT),bruinize(value)(ctx.append(typeT,name)))
      case Var(name) => Bruijn(ctx.getIndexByName(name))
 */